package service

import (
	"context"
	"fmt"
	"grpc/basic/global"
	__ "grpc/basic/proto"
	"grpc/handle/model"
	"grpc/pkg"
	"math/rand"
	"strconv"
	"time"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	//pb.UnimplementedGreeterServer
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {

	i, _ := global.Rdb.Get(global.Ctx, "SendSms_"+in.Phone).Int()
	if i >= 5 {
		return nil, fmt.Errorf("同一手机号每天最多请求验证码5次")
	}

	sms := rand.Intn(900000) + 100000
	sendSms, err := pkg.SendSms(in.Phone, strconv.Itoa(sms))
	if err != nil {
		return nil, err
	}

	if sendSms.Code != 2 {
		return nil, fmt.Errorf("短信发送失败")
	}

	global.Rdb.Set(global.Ctx, "sendSms_"+in.Phone, sms, time.Minute*50)

	global.Rdb.Incr(global.Ctx, "SendSms_"+in.Phone)
	global.Rdb.Expire(global.Ctx, "SendSms_"+in.Phone, time.Hour*24)

	return &__.SendSmsResp{
		Greet: "短信发送成功",
	}, nil
}

func (s *Server) Adduser(_ context.Context, in *__.AdduserReq) (*__.AdduserResp, error) {
	var user model.User
	user = model.User{
		Phone:    in.Phone,
		Password: in.Password,
		Username: fmt.Sprintf("游客_%d", rand.Intn(900)+100),
	}

	if err := user.VeryPhone(global.DB, in.Phone); err == nil {
		return nil, fmt.Errorf("手机号已注册")
	}

	result, _ := global.Rdb.Get(global.Ctx, "sendSms_"+in.Phone).Result()
	if result != in.Send {
		return nil, fmt.Errorf("验证码错误")
	}

	if err := user.Adduser(global.DB); err != nil {
		return nil, fmt.Errorf("注册失败")
	}

	return &__.AdduserResp{
		Greet:  "用户注册成功",
		UserId: int64(user.ID),
	}, nil
}

func (s *Server) QueryUser(_ context.Context, in *__.QueryUserReq) (*__.QueryUserResp, error) {
	var user model.User

	if err := user.VeryPhone(global.DB, in.Phone); err != nil {
		return nil, fmt.Errorf("手机号不存在")
	}

	result, _ := global.Rdb.Get(global.Ctx, "sendSms_"+in.Phone).Result()
	if result != in.Send {
		return nil, fmt.Errorf("验证码错误")
	}

	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}

	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return nil, err
	}

	return &__.QueryUserResp{
		Greet:    "用户登录成功",
		UserId:   int64(user.ID),
		Phone:    user.Phone,
		Username: user.Username,
		Token:    handler,
	}, nil
}

func (s *Server) ListUser(_ context.Context, in *__.ListUserReq) (*__.ListUserResp, error) {
	var user model.User

	if err := user.VeryUser(global.DB, in.UserId); err != nil {
		return nil, fmt.Errorf("用户不存在")
	}

	if user.Status != "会员" {
		return nil, fmt.Errorf("会员过期")
	}

	listUser, err := user.ListUser(global.DB, in.UserId, in.Page, in.Size)
	if err != nil {
		return nil, fmt.Errorf("用户推荐失败")
	}

	return &__.ListUserResp{
		Greet: "用户推荐列表",
		List:  listUser,
	}, nil
}
